<script setup lang="ts">
import type { UploadFile } from 'ant-design-vue';

import type { SubmitResult } from 'vue-element-plus-x/types/EditorSender';

import type { MessageItem } from './components/chat';

import { reactive, ref } from 'vue';

import {
  BookOutlined,
  DeleteOutlined,
  FileTextOutlined,
  MessageOutlined,
  PlusOutlined,
} from '@ant-design/icons-vue';
import {
  Avatar,
  Button,
  Card,
  Layout,
  message,
  Modal,
  Typography,
} from 'ant-design-vue';

import { ChatBubbleList, ChatSender } from './components/chat';

const { Sider, Content } = Layout;
const { Title, Paragraph, Text } = Typography;

// 助手数据
const recentUsedAssistant = reactive([
  {
    id: 0,
    title: '客服助手',
    description: '智能客服,回答用户问题',
    checked: true,
    icon: MessageOutlined,
  },
  {
    id: 1,
    title: '知识助手',
    description: '基于知识库的问答助手',
    checked: false,
    icon: BookOutlined,
  },
  {
    id: 2,
    title: '业务助手',
    description: '业务咨询和指导',
    checked: false,
    icon: FileTextOutlined,
  },
]);

// 聊天消息类型定义
type MessageRole = 'ai' | 'user';
interface Message {
  id: number;
  role: MessageRole;
  content: string;
  timestamp: string;
  loading?: boolean;
}

// BubbleList 消息类型
type BubbleMessage = MessageItem;

// 会话类型定义
interface Conversation {
  id: number;
  title: string;
  timestamp: string;
  selected: boolean;
  messages: Message[];
}

// 预设提示词类型定义
interface Prompt {
  id: number;
  title: string;
  content: string;
  category: string;
}

// 上传文件类型定义（FilesCard 格式）
interface UploadedFile {
  id: string;
  name: string;
  size: number;
  type: string;
  status?: 'error' | 'success' | 'uploading';
  url?: string;
}

// 聊天消息数据
const messages = ref<Message[]>([
  {
    id: 1,
    role: 'ai',
    content: '您好！我是AI助手,很高兴为您服务。请问有什么可以帮助您的吗?',
    timestamp: new Date().toLocaleTimeString(),
  },
]);

// BubbleList 消息数据
const bubbleMessages = ref<BubbleMessage[]>([
  {
    key: 1,
    role: 'ai',
    content: '您好！我是AI助手,很高兴为您服务。请问有什么可以帮助您的吗?',
    timestamp: new Date().toLocaleTimeString(),
    placement: 'start',
    noStyle: false,
  },
]);

// 头像配置
const userAvatar = ref('https://randomuser.me/api/portraits/men/32.jpg');
const aiAvatar = ref(
  'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
);

// 输入内容
const inputContent = ref('');

// 会话历史
const conversationHistory = ref<Conversation[]>([
  {
    id: 1,
    title: '新对话',
    timestamp: '12:00',
    selected: true,
    messages: [...messages.value],
  },
]);

// 当前选中的会话ID
const currentConversationId = ref(1);

// 预设提示词
const presetPrompts = ref<Prompt[]>([
  {
    id: 1,
    title: '解释概念',
    content: '请用简单易懂的语言解释一下[概念名称],并提供一些实际应用的例子。',
    category: '通用',
  },
  {
    id: 2,
    title: '代码优化',
    content:
      '请帮我优化以下代码,提高性能并改进可读性:\n\n```\n// 在这里粘贴您的代码\n```',
    category: '编程',
  },
  {
    id: 3,
    title: '总结内容',
    content:
      '请总结以下内容的主要观点,用简洁明了的方式呈现:\n\n[在这里粘贴需要总结的内容]',
    category: '通用',
  },
  {
    id: 4,
    title: '写作助手',
    content: '请帮我润色以下文字,使其更流畅、专业:\n\n[在这里粘贴您的文字]',
    category: '写作',
  },
]);

// 提示词面板显示状态（移到子组件）
// const showPrompts = ref(false); // 已移动到 ChatSender 组件

// 加载状态
const isLoading = ref(false);

// 联网搜索开关
const enableWebSearch = ref(false);

// 深度思考开关
const enableDeepThinking = ref(false);

// 上传的文件列表
const uploadedFiles = ref<UploadedFile[]>([]);

// 文件上传列表
const fileList = ref<UploadFile[]>([]);

// 获取当前会话
const getCurrentConversation = () => {
  return conversationHistory.value.find(
    (c) => c.id === currentConversationId.value,
  );
};

// 转换消息格式
const convertToBubbleMessage = (msg: Message): BubbleMessage => {
  return {
    key: msg.id,
    role: msg.role,
    content: msg.content,
    timestamp: msg.timestamp,
    placement: msg.role === 'ai' ? 'start' : 'end',
    noStyle: false,
    loading: msg.loading,
  } as BubbleMessage;
};

// 处理助手选择
const handleSelectAssistant = (id: number) => {
  recentUsedAssistant.forEach((assistant) => {
    assistant.checked = assistant.id === id;
  });

  // 清空当前会话并显示新助手的欢迎消息
  const conversation = getCurrentConversation();
  if (conversation) {
    const selectedAssistant = recentUsedAssistant.find((a) => a.id === id);
    const welcomeMessage: Message = {
      id: Date.now(),
      role: 'ai',
      content: `您好！我是${selectedAssistant?.title},很高兴为您服务。请问有什么可以帮助您的吗?`,
      timestamp: new Date().toLocaleTimeString(),
    };
    conversation.messages = [welcomeMessage];
    messages.value = [...conversation.messages];
    bubbleMessages.value = [convertToBubbleMessage(welcomeMessage)];
  }
};

// 切换会话
const switchConversation = (id: number) => {
  conversationHistory.value.forEach((conv) => {
    conv.selected = conv.id === id;
  });

  currentConversationId.value = id;
  const conversation = getCurrentConversation();
  if (conversation) {
    messages.value = [...conversation.messages];
    bubbleMessages.value = conversation.messages.map(convertToBubbleMessage);
  }
};

// 创建新会话
const createNewConversation = () => {
  const newId = Math.max(...conversationHistory.value.map((c) => c.id), 0) + 1;
  const welcomeMessage: Message = {
    id: Date.now(),
    role: 'ai',
    content: '您好！我是AI助手,很高兴为您服务。请问有什么可以帮助您的吗?',
    timestamp: new Date().toLocaleTimeString(),
  };
  const newConversation: Conversation = {
    id: newId,
    title: '新对话',
    timestamp: new Date().toLocaleTimeString(),
    selected: true,
    messages: [welcomeMessage],
  };

  conversationHistory.value.forEach((conv) => {
    conv.selected = false;
  });

  conversationHistory.value.unshift(newConversation);
  currentConversationId.value = newId;
  messages.value = [...newConversation.messages];
  bubbleMessages.value = [convertToBubbleMessage(welcomeMessage)];
};

// 删除会话
const deleteConversation = (id: number) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个会话吗?删除后不可恢复。',
    onOk() {
      const index = conversationHistory.value.findIndex((c) => c.id === id);
      if (index !== -1) {
        conversationHistory.value.splice(index, 1);

        // 如果删除的是当前会话,切换到第一个会话
        if (
          id === currentConversationId.value &&
          conversationHistory.value.length > 0
        ) {
          const firstConv = conversationHistory.value[0];
          if (firstConv) {
            switchConversation(firstConv.id);
          }
        } else if (conversationHistory.value.length === 0) {
          createNewConversation();
        }
      }
    },
  });
};

// 复制消息内容
const handleCopy = (content: string) => {
  // 已在组件中处理
};

// 重新生成消息
const handleRegenerate = (messageId: number) => {
  const messageIndex = bubbleMessages.value.findIndex(
    (m) => m.key === messageId,
  );
  const currentMessage = bubbleMessages.value[messageIndex];
  if (messageIndex !== -1 && currentMessage && currentMessage.role === 'ai') {
    currentMessage.loading = true;

    setTimeout(() => {
      const msg = bubbleMessages.value[messageIndex];
      if (msg) {
        bubbleMessages.value[messageIndex] = {
          ...msg,
          content:
            '这是重新生成的AI回复。在实际应用中,这里会重新调用AI服务获取新的回答。',
          loading: false,
        } as BubbleMessage;
      }
    }, 1500);
  }
};

// 收藏消息
const handleFavorite = (messageId: number) => {
  // 已在组件中处理
};

// 搜索消息
const handleSearch = (content: string) => {
  message.info(`搜索: ${content}`);
};

// 应用预设提示词（已移到子组件）
// const applyPrompt = (prompt: Prompt) => {
//   inputContent.value = prompt.content;
//   showPrompts.value = false;
// };

// 发送消息
const sendMessage = (payload: SubmitResult) => {
  if (!payload.text.trim()) return;

  // 构建消息内容
  let messageContent = payload.text;
  // 如果有上传的文件，添加文件信息
  if (uploadedFiles.value.length > 0) {
    messageContent += '\n\n📎 附件：';
    uploadedFiles.value.forEach((file: UploadedFile) => {
      messageContent += `\n- ${file.name} (${(file.size / 1024).toFixed(2)} KB)`;
    });
  }

  // 添加用户消息
  const userMessage: Message = {
    id: Date.now(),
    role: 'user',
    content: messageContent,
    timestamp: new Date().toLocaleTimeString(),
  };

  messages.value.push(userMessage);
  bubbleMessages.value.push(convertToBubbleMessage(userMessage));

  // 更新当前会话
  const conversation = getCurrentConversation();
  if (conversation) {
    conversation.messages.push(userMessage);
    conversation.timestamp = userMessage.timestamp;
    // 如果是第一条用户消息,更新会话标题
    if (conversation.messages.length === 2) {
      conversation.title =
        inputContent.value.slice(0, 20) +
        (inputContent.value.length > 20 ? '...' : '');
    }
  }

  // 清空输入框和文件
  const tempContent = inputContent.value;
  inputContent.value = '';
  const hasFiles = uploadedFiles.value.length > 0;
  const hasWebSearch = enableWebSearch.value;
  const hasDeepThinking = enableDeepThinking.value;
  uploadedFiles.value = [];
  fileList.value = [];

  // 添加AI回复占位符
  const aiMessageId = Date.now() + 1;
  const aiMessage: Message = {
    id: aiMessageId,
    role: 'ai',
    content: '',
    timestamp: new Date().toLocaleTimeString(),
    loading: true,
  };
  messages.value.push(aiMessage);
  bubbleMessages.value.push(convertToBubbleMessage(aiMessage));

  // 模拟AI回复
  isLoading.value = true;
  setTimeout(() => {
    isLoading.value = false;

    // 更新AI消息内容
    const messageIndex = messages.value.findIndex((m) => m.id === aiMessageId);
    const bubbleIndex = bubbleMessages.value.findIndex(
      (m) => m.key === aiMessageId,
    );

    // 构建AI回复内容
    let aiContent = `感谢您的提问！您刚才说:"${tempContent}"\n\n`;

    // 添加功能标识
    const features = [];
    if (hasWebSearch) features.push('🌐 联网搜索');
    if (hasDeepThinking) features.push('🧠 深度思考');
    if (hasFiles) features.push('📎 文件分析');

    if (features.length > 0) {
      aiContent += `启用功能: ${features.join(' | ')}\n\n`;
    }

    if (hasWebSearch) {
      aiContent +=
        '🔍 正在联网搜索相关信息...\n已为您搜索到最新的网络资源。\n\n';
    }

    if (hasDeepThinking) {
      aiContent += '💭 深度思考中...\n正在进行多角度分析和推理。\n\n';
    }

    if (hasFiles) {
      aiContent += '📄 文件分析完成\n已解析上传的文件内容。\n\n';
    }

    aiContent +=
      '这是一个AI生成的回复示例。在实际应用中,这里会连接到AI服务获取真实的回答。\n\n您可以尝试使用预设提示词来获得更好的AI回复效果。';

    if (messageIndex !== -1) {
      messages.value[messageIndex] = {
        ...aiMessage,
        content: aiContent,
        loading: false,
      };

      // 更新会话中的消息
      if (conversation) {
        const convMessageIndex = conversation.messages.findIndex(
          (m) => m.id === aiMessageId,
        );
        if (convMessageIndex !== -1) {
          conversation.messages[convMessageIndex] =
            messages.value[messageIndex];
        }
      }
    }

    if (bubbleIndex !== -1) {
      const msg = bubbleMessages.value[bubbleIndex];
      if (msg) {
        bubbleMessages.value[bubbleIndex] = {
          ...msg,
          content: aiContent,
          loading: false,
        };
      }
    }
  }, 1500);
};

// 处理 Sender 发送
const handleSenderSend = (payload: SubmitResult) => {
  sendMessage(payload);
};
</script>

<template>
  <Layout class="h-full bg-gray-50 dark:bg-gray-900">
    <!-- 左侧侧边栏 -->
    <Sider
      width="280"
      theme="light"
      class="border-r bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800"
    >
      <div class="p-4">
        <!-- 标题和新建会话按钮 -->
        <div class="mb-4 flex items-center justify-between">
          <Title :level="4" class="m-0 text-gray-800 dark:text-gray-100">
            AI助手
          </Title>
          <Button
            type="primary"
            size="small"
            @click="createNewConversation"
            class="bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600"
          >
            <PlusOutlined />
            新建会话
          </Button>
        </div>

        <!-- AI助手选择区域 -->
        <div class="mb-6">
          <Text
            type="secondary"
            class="mb-2 block text-sm font-medium dark:text-gray-400"
          >
            最近使用
          </Text>
          <div class="grid grid-cols-1 gap-2">
            <Card
              v-for="assistant in recentUsedAssistant"
              :key="assistant.id"
              :class="
                assistant.checked
                  ? 'border-blue-500 shadow-md dark:bg-blue-900/20'
                  : 'border-gray-200 hover:border-blue-300 dark:border-gray-700 dark:bg-gray-700/50 dark:hover:border-blue-600'
              "
              hoverable
              @click="handleSelectAssistant(assistant.id)"
              size="small"
            >
              <div class="flex items-center gap-3">
                <Avatar
                  :class="
                    assistant.checked
                      ? 'bg-blue-500 text-white'
                      : 'bg-gray-100 text-gray-600 dark:bg-gray-600 dark:text-gray-300'
                  "
                  size="small"
                >
                  <template #icon>
                    <component :is="assistant.icon" />
                  </template>
                </Avatar>
                <div class="min-w-0 flex-1">
                  <div
                    :class="
                      assistant.checked
                        ? 'font-medium text-blue-600 dark:text-blue-400'
                        : 'text-gray-800 dark:text-gray-200'
                    "
                    class="truncate text-sm"
                  >
                    {{ assistant.title }}
                  </div>
                  <Text
                    type="secondary"
                    class="block truncate text-xs dark:text-gray-400"
                  >
                    {{ assistant.description }}
                  </Text>
                </div>
              </div>
            </Card>
          </div>
        </div>

        <!-- 会话历史区域 -->
        <div>
          <div class="mb-2 flex items-center justify-between">
            <Text
              type="secondary"
              class="text-sm font-medium dark:text-gray-400"
            >
              会话历史
            </Text>
            <Text type="secondary" class="text-xs dark:text-gray-500">
              {{ conversationHistory.length }} 个会话
            </Text>
          </div>
          <div class="overflow-hidden rounded-lg border dark:border-gray-700">
            <div
              v-for="item in conversationHistory"
              :key="item.id"
              class="cursor-pointer border-b p-3 transition-all duration-200 last:border-b-0 dark:border-gray-700"
              :class="[
                item.selected
                  ? 'border-l-4 border-l-blue-500 bg-blue-50 dark:bg-blue-900/20'
                  : 'hover:bg-gray-50 dark:hover:bg-gray-700/50',
              ]"
              @click="switchConversation(item.id)"
            >
              <div class="flex w-full items-center justify-between">
                <div class="min-w-0 flex-1">
                  <div class="truncate text-sm dark:text-gray-200">
                    {{ item.title }}
                  </div>
                  <Text
                    type="secondary"
                    class="mt-1 block text-xs dark:text-gray-400"
                  >
                    {{ item.timestamp }}
                  </Text>
                </div>
                <Button
                  type="text"
                  size="small"
                  class="text-red-500 hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-900/20 dark:hover:text-red-300"
                  @click.stop="deleteConversation(item.id)"
                >
                  <DeleteOutlined />
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Sider>

    <!-- 右侧聊天区域 -->
    <Layout class="flex-1">
      <Content class="flex h-full flex-col p-0">
        <!-- 聊天消息区域 -->
        <div
          class="flex-1 overflow-hidden bg-gradient-to-b from-gray-50 to-gray-100 p-6 dark:from-gray-800 dark:to-gray-900"
        >
          <div class="mx-auto h-full max-w-4xl">
            <ChatBubbleList
              :messages="bubbleMessages"
              :user-avatar="userAvatar"
              :ai-avatar="aiAvatar"
              @copy="handleCopy"
              @regenerate="handleRegenerate"
              @favorite="handleFavorite"
              @search="handleSearch"
            />
          </div>
        </div>

        <!-- 输入区域 -->
        <div
          class="border-t bg-white p-6 shadow-inner dark:border-gray-700 dark:bg-gray-800"
        >
          <div class="mx-auto max-w-4xl">
            <!-- ChatSender 组件（包含所有功能） -->
            <ChatSender
              v-model="inputContent"
              v-model:uploaded-files="uploadedFiles"
              v-model:enable-web-search="enableWebSearch"
              v-model:enable-deep-thinking="enableDeepThinking"
              :loading="isLoading"
              :preset-prompts="presetPrompts"
              placeholder="💬 输入消息..."
              @send="handleSenderSend"
            />
          </div>
        </div>
      </Content>
    </Layout>
  </Layout>
</template>

<style lang="css" scoped>
:deep(.ant-layout) {
  height: 100%;
}

:deep(.ant-sider) {
  height: 100%;
  overflow-y: auto;
  box-shadow: 2px 0 8px rgb(0 0 0 / 5%);
}

:deep(.ant-sider::-webkit-scrollbar) {
  width: 6px;
}

:deep(.ant-sider::-webkit-scrollbar-track) {
  background: #f1f1f1;

  .dark & {
    background: #374151;
  }
}

:deep(.ant-sider::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 3px;

  .dark & {
    background: #6b7280;
  }
}

:deep(.ant-sider::-webkit-scrollbar-thumb:hover) {
  background: #a1a1a1;

  .dark & {
    background: #9ca3af;
  }
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;

  .dark & {
    background: #374151;
  }
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;

  .dark & {
    background: #6b7280;
  }
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;

  .dark & {
    background: #9ca3af;
  }
}

/* 功能开关区域样式 */
:deep(.ant-switch) {
  transition: all 0.3s ease;
}

:deep(.ant-switch-checked) {
  background-color: #1890ff;
}

/* 功能标签样式 */
:deep(.ant-badge-count) {
  box-shadow: 0 0 0 1px #fff;

  .dark & {
    box-shadow: 0 0 0 1px #1f2937;
  }
}

/* FilesCard 暗黑模式样式 */
:deep(.files-card) {
  .dark & {
    background: transparent;
  }
}

:deep(.file-item) {
  .dark & {
    background: #1f2937;
    border-color: #374151;
  }

  &:hover {
    .dark & {
      background: #374151;
      border-color: #4b5563;
    }
  }
}

:deep(.file-item-name) {
  .dark & {
    color: #e5e7eb;
  }
}

:deep(.file-item-size) {
  .dark & {
    color: #9ca3af;
  }
}

:deep(.file-item-icon) {
  .dark & {
    color: #60a5fa;
  }
}

:deep(.file-item-remove) {
  .dark & {
    color: #f87171;

    &:hover {
      background: #7f1d1d;
    }
  }
}
</style>
